package com.kadron.creator;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kadron.dao.KImageDAO;
import com.kadron.dao.KOrderDAO;
import com.kadron.dao.KOrderItemDAO;
import com.kadron.datamodel.KModelCreator;
import com.kadron.entity.KItemImage;
import com.kadron.entity.Order;
import com.kadron.entity.OrderItem;
import com.kadron.order.KOrderModel;
import com.kadron.order.OrderItemData;

public class KOrderModelCreator implements KModelCreator {

	/**
	 * 
	 */
	private static final long serialVersionUID = 485240113799077333L;
	
	private static final Log log = LogFactory.getLog(KOrderModelCreator.class);

	private KOrderDAO orderDAO;
	private KOrderItemDAO orderItemDAO;
	private KImageDAO imageDAO;
	
	public KOrderModelCreator(KOrderDAO orderDAO, KOrderItemDAO orderItemDAO,
			KImageDAO imageDAO) {
		super();
		this.orderDAO = orderDAO;
		this.orderItemDAO = orderItemDAO;
		this.imageDAO = imageDAO;
	}

	@Override
	public KOrderModel create(long id) {
		if (id <= 0) {
			log.error("id is <= 0");
			return null;
		}
		Order order = (Order) orderDAO.find(id, Order.class);
		KOrderModel model = new KOrderModel(order);
		List<OrderItem> orderItems = orderItemDAO.getOrderItems(id);
		List<OrderItemData> items = new ArrayList<OrderItemData>();
		BigDecimal total = new BigDecimal(0);
		for (OrderItem oi : orderItems) {
			KItemImage img = imageDAO.getMainItemImage(oi.getItem().getId());
			if (img == null) {
				img = imageDAO.getItemImage(oi.getItem().getId());				
			}
//			BigDecimal priceMath = new BigDecimal(oi.getPrice());				
//			BigDecimal taxPriceMath = new BigDecimal(oi.getTaxPrice());
			BigDecimal sum = oi.getSum();
			total = total.add(sum);
			OrderItemData data = new OrderItemData(oi, img);
			items.add(data);
		}
		total = total.setScale(2, RoundingMode.HALF_UP);
		model.setTotal(total);
		model.getItems().addAll(items);
		return model;
	}
	
}
